import { getLayoutProps } from "@/common/layout/getProps";
import { PlusOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import type { Key} from "react";
import { useState,useEffect } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import { Button, Divider, Form, Input, Modal, Row, Table, Pagination, message } from "antd";
import type { TableColumnsType , TableProps } from "antd";
import { ProForm } from "@/components/ProForm";
import { http } from "@/utils/request";
import axios from 'axios';

type TableDataType = {
  code: string;
  name: string;
  evaluType: string;
  createDeptName: string;
  evaluPersion: string;
  createdBy: string;
  createdTime: string;
  updatedByName: string;
  updatedTime: string;
  auditStatus: string;
}

type TableRowSelection<T> = TableProps<T>["rowSelection"];

const { confirm } = Modal;
const Index = () => {
  const router = useRouter();
  const [form] = Form.useForm()
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const columns: TableColumnsType<TableDataType> = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "单据编号",
      dataIndex: "code"
    },
    {
      align: "center",
      title: "考核名称",
      dataIndex: "name"
    },
    {
      align: "center",
      title: "考核类型",
      dataIndex: "evaluType",
      render: (_, record) => {
        return (
          <>
            {record.evaluType === "1" && <span>部门</span>}
            {record.evaluType === "2" && <span>员工</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "所属部门",
      dataIndex: "createdDeptName"
    },
    {
      align: "center",
      title: "期间",
      dataIndex: "evaluPersion"
    },
    {
      align: "center",
      title: "创建人",
      dataIndex: "createdByName"
    },
    {
      align: "center",
      title: "创建时间",
      dataIndex: "createdTime"
    },
    {
      align: "center",
      title: "更新人",
      dataIndex: "updatedByName"
    },
    {
      align: "center",
      title: "更新时间",
      dataIndex: "updatedTime"
    },
    {
      align: "center",
      title: "状态",
      dataIndex: "auditStatus",
      render: (_, record) => {
        return (
          <>
            {record.auditStatus === "1" && <span>待提交</span>}
            {record.auditStatus === "2" && <span>审核中</span>}
            {record.auditStatus === "3" && <span>已完成</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "操作",
      render: (_, record, index) => {
        return (
          <>
            <Button type={'link'} onClick={() => {
              router.push(`/performanceAppraise/departmentAppraise/departmentAppraiseDetail?id=${record.id}&type=detail`)
            }}>详情</Button>
            <Button type={'link'} onClick={() => {
              router.push(`/performanceAppraise/departmentAppraise/departmentAppraiseEdit?id=${record.id}`)
            }}>编辑</Button>
            <Button type={'link'} danger onClick={() => {
               confirm({
                title: '提示?',
                content: '此操作将永久删除该数据，是否继续?',
                cancelText:'取消',
                okText:'确定',
                onOk() {
                  delData(record.id)
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}>删除</Button>
          </>
        )
      }
    }
  ]

  const onSelectChange = (keys: Key[]) => {
    console.log(keys);
    setSelectedRowKeys(keys)
  }

  const rowSelection: TableRowSelection<TableDataType> = {
    selectedRowKeys,
    onChange: onSelectChange
  }

  const lunchAppraise = () => {
    router.push(`/performanceAppraise/departmentAppraise/departmentAppraiseCreate`)
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  //删除
  const delData = async(id:number) =>{
    try {
      // const res = await axios({
      //   method:'delete',
      //   url:'/PmEvaluation/removePmEvaluation',
      //   params:{
      //     id:id,
      //   }
      // })
      const res = await http.delete({
        url:'/PmEvaluation/removePmEvaluation',
        params:{
          id:id,
        }
      })
      if(res.code==200){
        message.success('删除成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmEvaluation/pmDeptEvaluationList',
        params:{
          code:form.getFieldValue('code'),
          name:form.getFieldValue('name'),
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={getList} onReset={getList}>
        <Form.Item
          label={'单据编号'}
          name="code"
        >
          <Input placeholder="请输入单据编号" />
        </Form.Item>
        <Form.Item
          label={'考核名称'}
          name="name"
        >
          <Input placeholder="请输入考核名称" />
        </Form.Item>
      </ProForm>

      <Divider className={'my-[20px]'}></Divider>

      <Row className={'mb-[20px]'}>
        <Button type={'primary'} icon={<PlusOutlined />} onClick={lunchAppraise}>发起评价</Button>
      </Row>

      <Table
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        rowSelection={rowSelection}
        bordered
        pagination={false}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default Index;
